function concount(fname, trange, yrange)
%    CONCOUNT(FILENAME, XRANGE,YRANGE) plot the number of active connection
%    and living connection. Here active means the connection is performing
%    data transfer without idle period, which includes time out period. 
%    Example:
%           concount('con_count_1.out')

if (nargin < 1) | (nargin > 3)
   error('Wrong number of input arguments. Try help con.');
end

if nargin > 1
   stime = trange(1);
   etime = trange(2);
else
   stime = -1;
end

clf;
set(gcf,'Units','pixels');
set(gcf,'Position',[20 20 800 600]);

ldcmd = sprintf('load %s;', fname);
eval(ldcmd);
fnamehd = strtok(fname, '.');
asgncmd = sprintf('D = %s;', fnamehd);

eval(asgncmd);
clrcmd = sprintf('%s = [];', fnamehd);
eval(clrcmd);

[row col] = size(D);
if col < 4
   error('Not enough columns in data file.');
end

S = [];
numS = 0;
A = [];
numA = 0;


if stime > 0
   for i = 1:row
     if (stime <= D(i,1)) & (D(i,1) <= etime)
       numS = numS + 1;
       S(numS,:)=D(i,:);
       if D(i,4) > 0
         numA = numA + 1;
         A(numA,:) = D(i,:);
       end
     end
   end
   D = S;
   S = [];
else 
   for i = 1:row
     if D(i,4) > 0
         numA = numA + 1;
         A(numA,:) = D(i,:);
     end
   end
end

dplot = 0;
if ~isempty(D)
     %plot(D(:,1),D(:,2),'-.+b','MarkerSize',6);
     plot(D(:,1),D(:,2),'-b','MarkerSize',6);
     hold on;
     %plot(D(:,1),D(:,3),':sr','MarkerSize',2);
     plot(D(:,1),D(:,3),'-r','MarkerSize',2);
     dplot = 1;
end

     aplot = 0;
if ~isempty(A) 
     stem(A(:,1),A(:,4),'-g.');
%     plot(A(:,1),A(:,4),':sg','MarkerSize',2);
     aplot = 1;
end

%set(gca,'XTickLabel',' ');

ylabcmd = sprintf('ylabel(''connections & timeouts'');');
eval(ylabcmd);
xlabel('Time (seconds)');

if dplot == 1
   lgndcmd = '''living connections'', ''active connections'',';
else
   lgndcmd = '';
end
if aplot == 1
   lgndcmd = strcat(lgndcmd, '''timeout counting'', ');
end


if ~isempty(lgndcmd)
   lgndcmd = sprintf('legend(%s 2);', lgndcmd);
   eval(lgndcmd);
end

if stime >= 0
   set(gca, 'XLim', [stime etime]);
end
%set(gca, 'YLim', [0 300]);

fn = strrep(fname,'_','\_');
titcmd = sprintf('title(''%s'');', fn);
eval(titcmd);
box on;
grid on;
hold off;

[I,map] = capture;
imcmd = sprintf('imwrite(I,map,''%s.jpg'',''jpeg'');', fnamehd);
eval(imcmd);

set(gcf,'PaperUnits','points');
set(gcf,'PaperPosition',[0 0 800 900]);
print(gcf, '-depsc', fnamehd);
